<template>
  <div class="home-navbar">
    <div class="navbar-container">
      <!-- Logo -->
      <div class="navbar-logo" @click="goHome">
        <span class="logo-text">求职招聘系统</span>
      </div>

      <!-- 导航菜单 -->
      <div class="navbar-menu">
        <div class="nav-menu">
          <div 
            v-for="item in menuItems" 
            :key="item.index"
            :class="['nav-item', { active: isRouteActive(item.index) }]"
            @click="handleMenuSelect(item.index)"
          >
            <el-icon v-if="item.icon" class="nav-icon"><component :is="item.icon" /></el-icon>
            <span class="nav-text">{{ item.label }}</span>
          </div>
        </div>
      </div>

      <!-- 用户信息区域 -->
      <div class="navbar-user">
        <el-dropdown @command="handleCommand" trigger="click">
          <div class="user-info">
            <el-avatar :size="40" class="user-avatar">
              <img v-if="userAvatar" :src="getAvatarUrl(userAvatar)" alt="头像" />
              <span v-else>{{ username.charAt(0).toUpperCase() }}</span>
            </el-avatar>
            <span class="username">{{ username }}</span>
            <el-icon class="dropdown-icon"><arrow-down /></el-icon>
          </div>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="profile">
                <el-icon><User /></el-icon>
                <span style="margin-left: 8px">个人中心</span>
              </el-dropdown-item>
              <el-dropdown-item divided command="logout">
                <el-icon><SwitchButton /></el-icon>
                <span style="margin-left: 8px">退出登录</span>
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import useStore from '@/store'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown, User, SwitchButton, House, Document, Briefcase, OfficeBuilding } from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()
const store = useStore()

const activeMenu = ref('/')

const username = computed(() => store.app.username || '用户')
const userAvatar = computed(() => store.app.avatar || '')
const role = computed(() => store.app.role || 'user')

// 菜单项配置
const menuItems = [
  { index: '/', label: '首页', icon: House },
  { index: '/enterprises', label: '企业', icon: OfficeBuilding },
  { index: '/interview/questions', label: '面试', icon: Briefcase },
  { index: '/resume/dashboard', label: '简历', icon: Document }
]

// 检查路由是否匹配
const isRouteActive = (menuPath) => {
  const currentPath = route.path
  if (menuPath === '/') {
    return currentPath === '/'
  }
  return currentPath.startsWith(menuPath)
}

// 更新激活菜单
const updateActiveMenu = () => {
  if (route.path === '/') {
    activeMenu.value = '/'
  } else if (route.path.startsWith('/enterprises')) {
    activeMenu.value = '/enterprises'
  } else if (route.path.startsWith('/interview')) {
    activeMenu.value = '/interview/questions'
  } else if (route.path.startsWith('/resume')) {
    activeMenu.value = '/resume/dashboard'
  } else {
    activeMenu.value = route.path
  }
}

onMounted(() => {
  updateActiveMenu()
})

// 监听路由变化
watch(() => route.path, () => {
  updateActiveMenu()
})

// 获取头像URL
const getAvatarUrl = (avatar) => {
  if (!avatar) return ''
  // 如果是完整URL，直接返回
  if (avatar.startsWith('http')) return avatar
  // 如果是相对路径，拼接后端地址
  if (avatar.startsWith('/public')) {
    return `http://localhost:7001${avatar}`
  }
  return avatar
}

const goHome = () => {
  router.push('/')
}

const handleMenuSelect = (index) => {
  router.push(index)
  activeMenu.value = index
}

const handleCommand = async (command) => {
  if (command === 'logout') {
    try {
      await ElMessageBox.confirm('确定要退出登录吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      })
      
      // 调用退出登录
      await store.app.logoutAction()
      ElMessage.success('已退出登录')
      
      // 跳转到登录页
      router.push({ name: 'Login' })
    } catch (error) {
      // 用户取消或接口失败，仍然执行退出
      if (error !== 'cancel') {
        await store.app.logoutAction()
        router.push({ name: 'Login' })
      }
    }
  } else if (command === 'profile') {
    // 跳转到个人中心（根据角色不同跳转到不同页面）
    if (role.value === 'admin') {
      router.push('/backend')
    } else if (role.value === 'enterprise') {
      router.push('/admin/enterprise-info')
    } else {
      // 普通用户跳转到个人中心（投递记录和统计）
      router.push('/personal-center')
    }
  }
}
</script>

<style lang="scss" scoped>
.home-navbar {
  position: sticky;
  top: 0;
  z-index: 1000;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  border-bottom: none;
}

.navbar-container {
  max-width: 1400px;
  margin: 0 auto;
  padding: 0 30px;
  height: 70px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.navbar-logo {
  cursor: pointer;
  display: flex;
  align-items: center;
  flex-shrink: 0;
  margin-right: 40px;
  transition: transform 0.3s;
  
  &:hover {
    transform: scale(1.05);
  }
  
  .logo-text {
    font-size: 24px;
    font-weight: 700;
    color: #fff;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.2);
    letter-spacing: 1px;
  }
}

.navbar-menu {
  flex: 1;
  display: flex;
  justify-content: center;
  min-width: 0; // 允许收缩
  
  .nav-menu {
    display: flex;
    align-items: center;
    gap: 8px;
    white-space: nowrap;
    overflow: visible; // 确保不隐藏
    
    .nav-item {
      display: flex;
      align-items: center;
      gap: 6px;
      padding: 10px 20px;
      border-radius: 8px;
      cursor: pointer;
      transition: all 0.3s ease;
      color: rgba(255, 255, 255, 0.9);
      font-size: 15px;
      font-weight: 500;
      white-space: nowrap;
      position: relative;
      
      .nav-icon {
        font-size: 18px;
      }
      
      .nav-text {
        font-size: 15px;
      }
      
      &:hover {
        background-color: rgba(255, 255, 255, 0.15);
        color: #fff;
        transform: translateY(-2px);
      }
      
      &.active {
        background-color: rgba(255, 255, 255, 0.25);
        color: #fff;
        box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
        
        &::after {
          content: '';
          position: absolute;
          bottom: 0;
          left: 50%;
          transform: translateX(-50%);
          width: 60%;
          height: 3px;
          background: #fff;
          border-radius: 2px;
        }
      }
    }
  }
}

.navbar-user {
  display: flex;
  align-items: center;
  flex-shrink: 0;
  margin-left: 20px;
  
  .user-info {
    display: flex;
    align-items: center;
    cursor: pointer;
    padding: 8px 16px;
    border-radius: 25px;
    background-color: rgba(255, 255, 255, 0.15);
    backdrop-filter: blur(10px);
    transition: all 0.3s ease;
    
    &:hover {
      background-color: rgba(255, 255, 255, 0.25);
      transform: translateY(-2px);
      box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
    }
    
    .user-avatar {
      margin-right: 10px;
      border: 2px solid rgba(255, 255, 255, 0.3);
      box-shadow: 0 2px 8px rgba(0, 0, 0, 0.2);
      
      img {
        width: 100%;
        height: 100%;
        object-fit: cover;
      }
      
      span {
        font-size: 16px;
        font-weight: 600;
        color: #fff;
      }
    }
    
    .username {
      font-size: 15px;
      color: #fff;
      font-weight: 600;
      margin-right: 8px;
      text-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
    }
    
    .dropdown-icon {
      font-size: 14px;
      color: rgba(255, 255, 255, 0.9);
      transition: transform 0.3s;
    }
  }
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  
  i {
    margin-right: 8px;
  }
}
</style>

